package com.cmpe451.nutty.security;

import java.util.Collection;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.vote.AbstractAccessDecisionManager;
import org.springframework.security.core.Authentication;

import com.cmpe451.nutty.so.GuiUser;

public class CustomAccessDecisionManager extends AbstractAccessDecisionManager {

	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException {

		GuiUser adminUser = null;
		if (authentication.getPrincipal() instanceof GuiUser) {
			adminUser = (GuiUser) authentication.getPrincipal();
		}

		int deny = 0;

		for (AccessDecisionVoter voter : getDecisionVoters()) {
			int result = voter.vote(authentication, object, configAttributes);

			switch (result) {
				case AccessDecisionVoter.ACCESS_GRANTED:
					return;
				case AccessDecisionVoter.ACCESS_DENIED:
					deny++;
					break;
				default:
					break;
			}
		}

		if (deny > 0) {
			// ecplicit deny
			throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
		}

		// String url = ((FilterInvocation) object).getRequest().getServletPath();
		// if (adminUser != null && CollectionUtils.containsAny(ALLOWED_ROLES,
		// adminUser.getRoles())) {
		// logger.warn("SECURITY AUDIT::Access granted for url SUSPICIOUSLY!!!. url = " + url);
		// return;
		// }

		throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
	}
}
